package com.bgdCA.controller;


import com.bgdCA.domain.Account;
import com.bgdCA.response.CodeMsg;
import com.bgdCA.response.Result;
import com.bgdCA.service.IMailService;
import com.bgdCA.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class RegisterController {
    @Autowired
    RegisterService registerService;
    @Autowired
    IMailService mailService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Transactional(propagation = Propagation.REQUIRED, rollbackForClassName = "Exception")
    @RequestMapping("/register")
    @ResponseBody
    public Result register(@RequestBody Account account) {

        //    System.out.println(registerUserInfo.toString());
        String username = account.getUsername();
        String password = account.getPassword();
        String mail = account.getMail();
        // String token = "";

//        查找用户
        Account account1 = registerService.findUser(username);
       //System.out.println(mail.toString());
        //       判断用户名是否重复
        if (account1 != null) {
            return Result.error(CodeMsg.REGISTER_USERNAME_ALREADY_USE);
        }

        if (redisTemplate.hasKey(username)) {
            return Result.error(CodeMsg.REGISTER_USERNAME_ALREADY_USE);
        }


        String[] to = new String[]{mail};

        System.out.println("to="+to[0].toString());

        String activeHref = "http://49.234.76.225:8080/AdminLTE-master/pages/BICC/email-confirm.html?token=" + username;


        mailService.registerTemplateMail(to, "register", activeHref);
        System.out.println("发送完毕");

        String key = username;

        //     redisTemplate.expire(key,1, TimeUnit.MINUTES);

        Map<String, Object> map1 = new HashMap<>();
        map1.put("username", username);
        map1.put("password", password);
        map1.put("mail", mail);

        // 一次性向hash中存放一个map
        redisTemplate.opsForHash().putAll(key, map1);
        redisTemplate.expire(key, 30, TimeUnit.DAYS);

        return Result.success(null);
    }
}
